package com.yangxk.kadmin.auth.service;

import com.yangxk.kadmin.auth.beans.WhiteListBean;
import com.yangxk.kadmin.auth.config.AuthConfigure;
import com.yangxk.kadmin.auth.dao.DbDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限相关逻辑实现类
 *
 * @author yangxk
 * @date 2018/9/9 14:19
 */
public class CoreService {

    private static final Map<String, String> ALL_AUTH = new HashMap<>();

    @Autowired
    private DbDao dbDao;

    @Autowired
    private WhiteListBean whiteListBean;

    @Autowired(required = false)
    private AuthConfigure authConfigure;

    /**
     * 当前请求是否可以通过
     * create by yangxk 2018/9/9 14:19
     */
    public boolean isPass(String url, HttpServletRequest request) {
        // spring boot的监控请求
        if (url.startsWith("/actuator")) {
            return true;
        }

        // 是否为白名单
        if (this.whiteListBean.getWhiteList().contains(url)) {
            return true;
        }
        // 校验权限
        return hasPermission(url, request);
    }

    /**
     * 获取当前登录用户的ID
     * create by yangxk 2018/9/9 14:20
     */
    public String userId(HttpServletRequest request) {

        if (authConfigure == null)
            throw new RuntimeException("权限相关配置未实现");
        return authConfigure.curentUserId(request);
    }

    /**
     * 从数据库中查询当前登录用户的权限ID集合
     * create by yangxk 2018/9/9 14:21
     */
    private List<String> findUserAuthIdsFromDb(String userId) {
        List<String> userAuth = dbDao.findUserAuthIds(userId);
        return userAuth;
    }

    /**
     * 获取当前登录用户的权限ID集合
     * 如果缓存中有则从缓存中获取，否则从数据库中查询
     * create by yangxk 2018/9/9 14:22
     */
    private List<String> findUserAuthIds(String userId) {
        // TODO  缓存
        return findUserAuthIdsFromDb(userId);
    }

    /**
     * 是否为超级管理员
     * create by yangxk 2018/9/9 14:21
     */
    private boolean isSuperAdmin() {
        // TODO 超级管理员判断条件
        return false;
    }

    /**
     * 判断是否有权限
     * create by yangxk 2018/9/9 14:23
     */
    private boolean hasPermission(String url, HttpServletRequest request) {
        if (isSuperAdmin()) return true;

        // 获取请求URL对应的权限ID
        String urlId = getAuthIdByUrl(url);
        // 获取登录用户的权限ID集合
        List<String> userAuthIds = findUserAuthIds(userId(request));
        if(!"".equals(urlId) && userAuthIds.contains(urlId)) {
            return true;
        }

        return false;
    }

    /**
     * 获取请求URL对应的权限ID
     * create by yangxk 2018/9/9 14:24
     */
    private String getAuthIdByUrl(String url) {
        if (ALL_AUTH.isEmpty()) { // 如果缓存为空，初始化缓存
            initAllAuth();
        }

        String id = ALL_AUTH.get(url);
        if (id == null)
            return "";
        return id;
    }

    /**
     * 初始化缓存
     * create by yangxk 2018/9/9 14:25
     */
    private void initAllAuth() {
        Map<String, String> allAuth = dbDao.findAllAuth();
        for (Map.Entry<String, String> entry : allAuth.entrySet()) {
            ALL_AUTH.put(entry.getKey(), entry.getValue());
        }
    }

}
